import { formatSongInfoFn } from './songMenu';

function getObject(key) {
  const value = localStorage.getItem(key);
  try {
    return value && JSON.parse(value);
  } catch (error) {
    return {};
  }
}

function setObject(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

function addSong(songInfo, front = true) {
  const formatSongInfo = formatSongInfoFn(songInfo);
  let playingList = getObject('playingList');
  const index = playingList.findIndex((item) => formatSongInfo.title === item.title && formatSongInfo.author === item.author);
  if (index !== -1) {
    playingList.splice(index, 1);
  }
  if (front) {
    playingList.unshift(formatSongInfo);
  } else {
    playingList.push(formatSongInfo);
  }
  setObject('playingList', playingList);
}

const localStorageProto = Object.getPrototypeOf(localStorage);
localStorageProto.getObject = getObject;
localStorageProto.setObject = setObject;
localStorageProto.addSong = addSong;
Object.setPrototypeOf(localStorage, localStorageProto);
